package com.vic.commons.utils;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by huangyp on 2014/10/17.
 */
public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger("info");
    public static String encoding;

    private static final HttpConnectionManager connectionManager;

    private static final HttpClient client;
    /** = */
    public static final String QSTRING_EQUAL = "=";

    /** & */
    public static final String QSTRING_SPLIT = "&";
    static {
        HttpConnectionManagerParams params = loadHttpConfFromFile();
        connectionManager = new MultiThreadedHttpConnectionManager();
        connectionManager.setParams(params);
        client = new HttpClient(connectionManager);
    }
    
    public static String createLinkString(Map<String, String> para, boolean sort, boolean encode) throws UnsupportedEncodingException {
        List<String> keys = new ArrayList<String>(para.keySet());
        if (sort)
            Collections.sort(keys);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = para.get(key);
            if (encode) {
                value = URLEncoder.encode(value, "utf-8");
            }
            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                sb.append(key).append(QSTRING_EQUAL).append(value);
            } else {
                sb.append(key).append(QSTRING_EQUAL).append(value).append(QSTRING_SPLIT);
            }
        }
        return sb.toString();
    }
	

    private static HttpConnectionManagerParams loadHttpConfFromFile(){
        Properties p  = new Properties();
        try {
            p.load(HttpUtil.class.getClassLoader().getResourceAsStream("httputil.properties"));
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        encoding = p.getProperty("http.content.encoding");

        HttpConnectionManagerParams params = new HttpConnectionManagerParams();
        params.setConnectionTimeout(Integer.parseInt(p.getProperty("http.connection.timeout")));
        params.setSoTimeout(Integer.parseInt(p.getProperty("http.so.timeout")));
        params.setStaleCheckingEnabled(Boolean.parseBoolean(p.getProperty("http.stale.check.enabled")));
        params.setTcpNoDelay(Boolean.parseBoolean(p.getProperty("http.tcp.no.delay")));
        params.setDefaultMaxConnectionsPerHost(Integer.parseInt(p.getProperty("http.default.max.connections.per.host")));
        params.setMaxTotalConnections(Integer.parseInt(p.getProperty("http.max.total.connections")));
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
        return params;
    }

    public static String post(String url, String encoding, String content) {
        try {
            byte[] resp = post(url, content.getBytes(encoding));
            if (null == resp)
                return null;
            return new String(resp, encoding);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }


    public static String post(String url, String content) {
        return post(url, encoding, content);
    }


    public static byte[] post(String url, byte[] content) {
        try {
            byte[] ret = post(url, new ByteArrayRequestEntity(content));
            return ret;
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] post(String url, RequestEntity requestEntity) throws Exception {

        PostMethod method = new PostMethod(url);
        method.addRequestHeader("Connection", "Keep-Alive");
        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
        method.setRequestEntity(requestEntity);
        method.addRequestHeader("Content-Type","application/x-www-form-urlencoded");

        try {
            int statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
            	 logger.error(url+" "+requestEntity+" "+statusCode);
                return method.getResponseBody();
            }
            return method.getResponseBody();

        } catch (SocketTimeoutException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        } finally {
            method.releaseConnection();
        }
    }
}
